<template>
  <div class="h-panel">
    <div class="h-panel-bar">
      <span class="h-panel-title">修改密码</span>
    </div>
    <div class="h-panel-body">
      <Form :valid-on-change="true" :show-error-tip="true" ref="pwdForm" label-position="left" :label-width="110" :rules="verify" :model="model">
        <FormInput label="账号" :readonly="!!userId" type="text" v-model="model.userId"></FormInput>
        <FormInput label="原密码" prop="passwd" type="password" v-model="model.passwd"></FormInput>
        <FormInput label="新密码" prop="newPasswd" type="password" v-model="model.newPasswd"></FormInput>
        <FormInput label="确认密码" prop="newPasswd2" type="password" v-model="model.newPasswd2"></FormInput>
        <FormItem>
          <Button color="primary" @click="submit">确认</Button>
          <Button class="h-btn" @click="close">返回</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script>
import Sm3 from "crypto-api/src/hasher/sm3";
import { toHex } from "crypto-api/src/encoder/hex";
export default {
  computed: {
    userId() {
      return this.$store.state.loginInfo.loginId;
    },
  },
  mounted() {},
  data() {
    return {
      opend: true,
      verify: {
        required: ["passwd", "newPasswd", "newPasswd2"],
      },
      model: {
        userId: this.$store.state.loginInfo.loginId,
        passwd: "",
        newPasswd: "",
        newPasswd2: "",
      },
    };
  },
  methods: {
    close() {
      this.$router.back();
    },
    submit() {
      let validResult = this.$refs.pwdForm.valid();
      if (validResult.result) {
        if (
          !this.model.newPasswd ||
          this.model.newPasswd != this.model.newPasswd2
        ) {
          this.model.newPasswd2 = "";
          this.$Message.error("再次输入密码不一至");
          return;
        }

        let sm3 = new Sm3();
        sm3.update(this.model.passwd);
        let passwd = toHex(sm3.finalize()).toUpperCase();
        sm3 = new Sm3();
        sm3.update(this.model.newPasswd);
        let newPasswd = toHex(sm3.finalize()).toUpperCase();

        this.$axios
          .put("/repasswd", {
            userId: this.model.userId,
            passwd: passwd,
            newPasswd: newPasswd,
          })
          .then((res) => {
            if (res.data.code == this.$store.state.SUCCESS) {
              this.$store.commit("LOGIN_FLAG", false);
              this.$axios.delete("/authorized");
              location.href = "/";
            } else {
              this.$Message.error(res.data.msg, 2000);
            }
          });
      }
    },
  },
};
</script>